package com.yc.cloud.openai.service.impl.tts;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.openai.dto.TTSResultDTO;
import com.yc.cloud.openai.dto.resp.ChatTTSResp;
import com.yc.cloud.openai.request.TTSParam;
import com.yc.cloud.openai.service.tts.TTSService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Service("ChatTTSServiceImpl")
public class ChatTTSServiceImpl implements TTSService {

    private static final String URL = "http://127.0.0.1:9966/tts";

    @Override
    public TTSResultDTO getTTSResult(TTSParam param) {
        val ttsStart = System.currentTimeMillis();
        val result = sendRequest(param.getContent());
        if (StrUtil.isEmpty(result)) {
            return null;
        }
        val chatTTSResp = JSONUtil.toBean(result, ChatTTSResp.class);
        if (chatTTSResp.getCode() != 0) {
            log.error("chat tts error:{}", chatTTSResp.getMsg());
            return null;
        }
        val audioFiles = chatTTSResp.getAudio_files().get(0);
        val audioUrl = audioFiles.getUrl();
        val audioBase64Data = Base64.encodeBase64String(HttpRequest.get(audioUrl).execute().bodyBytes());

        val ttsResultDTO = new TTSResultDTO();
        ttsResultDTO.setUrl(audioUrl);
        ttsResultDTO.setResult(audioBase64Data);
        val ttsEnd = System.currentTimeMillis();
        val costTime = ttsEnd - ttsStart;
        ttsResultDTO.setCostTime(costTime);
        return ttsResultDTO;
    }

    @Override
    public Mono<TTSResultDTO> getTTSResultByMono(TTSParam param) {
        val ttsResultDTO = getTTSResult(param);
        return Mono.just(ttsResultDTO);
    }


    private String sendRequest(String text) {

        // 创建一个Map对象，用于存放表单数据
        Map<String, Object> formData = new LinkedHashMap<>();
        formData.put("text", text);
        formData.put("prompt", "");
        formData.put("voice", "3333");
        formData.put("temperature", "0.3");
        formData.put("top_p", "0.7");
        formData.put("top_k", "20");
        formData.put("skip_refine", "0");
        formData.put("custom_voice", "0");

        // 使用HttpRequest发送POST请求，以application/x-www-form-urlencoded格式提交表单数据
        HttpRequest request = HttpRequest.post(URL)
                .form(formData);

        try (HttpResponse response = request.execute()) {
            // 打印响应内容
            return response.body();
        }
    }


    // 创建一个Map对象，用于存放请求参数
//        Map<String, Object> bodyMap = new HashMap<>();
//        bodyMap.put("text", "若不懂无需填写");
//        bodyMap.put("prompt", "");
//        bodyMap.put("voice", "3333");
//        bodyMap.put("temperature", 0.3);
//        bodyMap.put("top_p", 0.7);
//        bodyMap.put("top_k", 20);
//        bodyMap.put("skip_refine", 0);
//        bodyMap.put("custom_voice", 0);
//
//        // 使用HttpRequest发送POST请求，bodyMap将被自动转换为JSON字符串
//        HttpRequest request = HttpRequest.post(URL)
//                .body(JSONUtil.toJsonStr(bodyMap));
//
//        // 设置内容类型为 application/json
//        //  request.header("Content-Type", "application/json; charset=UTF-8");
//
//        try (HttpResponse response = request.execute()) {
//            // 打印响应内容
//            return response.body();
//        }
//    }
}
